/*
 * @Author: zeki mini
 * @Date: 2021-01-19 16:32:47
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-04-14 16:39:16
 * @Description: 创建订单
 */

import React, { Component } from 'react';
import {
  TouchableOpacity,
  StyleSheet,
  View,
  Text,
  SafeAreaView,
  Platform,
  TextInput,
  ScrollView
} from 'react-native';
import DateTimePicker from 'react-native-modal-datetime-picker';
import Moment from 'moment';
import { Button, BackImage, msg, Header, _, FormSelect } from '../../../../common';
import supply from '../../../../api/supply';
import CreatOrderItem from './components/creat-order-item';
import {
  px2dp, isAndroid, fontColorDeepGray, fontColorSecDeepGray,
  mainBgColorLightGray, splitLineColorLightGray, mainBgColorBlack,
  mainBgColorWhite, fontColorBlack, screenWidth, screenHeight
} from '../../../../common/styles';
import {
  fetchUnitList,
} from '../../../../api/source-release';
import SelectItem from '../release-source/components/select-item';

const { Submit } = Button;
export default class CreatOrder extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showCreatBox: false,
      invalidTimeStartStr: '',
      invalidTimeEndStr: '',
      isTimeShow: false,
      isTimeType: '',
      // unitList: [], //计量单位列表
      weight: null, // 重量 限量时必填
      weightUnit: '', // 重量单位
      disabled: false
    };
  }

  onBackFunc = () => {
    msg.emit('router: back');
  }

  // 获取计量单位列表
  fetchUnitList = () => {
    const { } = this.state;
    fetchUnitList({}).then((res) => {
      if (res.success) {
        this.setState({ unitList: res.data });
      }
    });
  };

  // 转义单位
  matchingUnit(unit, unitList) {
    if (!unit || unitList.length === 0) {
      return '';
    }
    if (unitList.length > 0) {
      const unitName = unitList.filter(u => u.code === unit);
      if (unitName.length > 0) {
        return unitName[0].name;
      }
      return unit;
    }
    return unit;
  }

  // 改变
  onChange = (type, val) => {
    this.setState({ [type]: val });
  }

  handleConfirm = (val) => {
    const { isTimeType, invalidTimeStartStr, invalidTimeEndStr } = this.state;
    this.setState({ [isTimeType]: Moment(val).format('YYYY-MM-DD') });
    this.setState({ isTimeShow: false });
  };

  handleCancel = (val) => {
    this.setState({ isTimeShow: false });
  };

  // 修改重量
  onChangeWeight = (val) => {
    const { weight } = this.state;
    if (/\D/g.test(val)) {
      const val1 = val.replace(/\D/g, '');
      this.setState({ weight: val1 });
      return;
    }
    this.setState({ weight: val });
  };

  // 提交
  contractOrderCreat = () => {
    const { invalidTimeStartStr, invalidTimeEndStr, weight, weightUnit } = this.state;
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { item } = params;
    if (invalidTimeStartStr === null || invalidTimeStartStr === undefined || invalidTimeStartStr === '') {
      msg.emit('app:tip', { text: '请完善必填信息' });
      return;
    }
    if (invalidTimeEndStr === null || invalidTimeEndStr === undefined || invalidTimeEndStr === '') {
      msg.emit('app:tip', { text: '请完善必填信息' });
      return;
    }
    if (weight === null || weight === undefined || weight === '') {
      msg.emit('app:tip', { text: '请完善必填信息' });
      return;
    }
    if (Moment(invalidTimeStartStr).unix('X') > Moment(invalidTimeEndStr).unix('X')) {
      msg.emit('app:tip', { text: '截止日期不能早于起始日期' });
      return;
    }
    this.setState({ disabled: true });
    supply.contractOrderCreat({
      contractId: item.contractId,
      orderStartTime: `${invalidTimeStartStr} ` + '00:00:00',
      orderEndTime: `${invalidTimeEndStr} ` + '23:59:59',
      weight: weight,
      weightUnit: item.weightUnit
    }).then(res => {
      if (res.success) {
        msg.emit('app:tip', { text: '创建成功' });
        setTimeout(() => {
          this.setState({ disabled: false });
          msg.emit('router: refreshRoute', {
            routeName: 'ShipperSource',
          });
          msg.emit('router: goToNext', {
            routeName: 'ShipperSource',
          });
        }, 1500);
      } else {
        this.setState({ disabled: false });
        msg.emit('app:tip', { text: res.msg });
        // setTimeout(() => {
        //   msg.emit('router: refreshRoute', {
        //     routeName: 'ShipperSource',
        //   })
        //   msg.emit('router: goToNext', {
        //     routeName: 'ShipperSource',
        //   });
        // }, 1500);
      }
    }).catch(err => {
      this.setState({ disabled: false });
    });
  }

  render() {
    const {
      showCreatBox,
      invalidTimeStartStr,
      invalidTimeEndStr,
      isTimeShow,
      isTimeType,
      weight,
      weightUnit,
      disabled
    } = this.state;
    let supplyName = null;
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { item, unitList } = params;
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: mainBgColorLightGray }}>
        <Header
          title='创建订单'
          renderLeft={() => {
            return (
              <TouchableOpacity
                activeOpacity={0.8}
                style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
                  { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
                onPress={this.onBackFunc}
              >
                <BackImage />
              </TouchableOpacity>
            );
          }}
        />
        <CreatOrderItem
          logisticsObj={item}
          unitList={unitList}
        />
        <ScrollView
          style={{
            width: '100%',
            maxHeight: 0.8 * screenHeight,
          }}
          showsVerticalScrollIndicator={false}
        >
          <View style={styles.floorWrap}>
            {/* 是否限期 */}
            <View style={styles.packing}>
              <View style={styles.itemHeader}>
                <Text
                  style={{
                    fontSize: px2dp(28),
                    fontWeight: 'bold',
                    color: mainBgColorBlack,
                  }}
                >
                  发货日期
                  {' '}
                </Text>
              </View>
              <View
                style={{
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  marginTop: px2dp(24),
                }}
              >
                <TouchableOpacity
                  style={[styles.startAndEndTimeWrap]}
                  onPress={() => {
                    this.setState({
                      isTimeShow: true,
                      isTimeType: 'invalidTimeStartStr',
                    });
                  }}
                  activeOpacity={0.8}
                >
                  <Text>{invalidTimeStartStr || '必填，起始日期'}</Text>
                </TouchableOpacity>
                <View style={styles.timeLine} />
                <TouchableOpacity
                  style={[styles.startAndEndTimeWrap]}
                  onPress={() => {
                    this.setState({
                      isTimeShow: true,
                      isTimeType: 'invalidTimeEndStr',
                    });
                  }}
                  activeOpacity={0.8}
                >
                  <Text>{invalidTimeEndStr || '必填，截止日期'}</Text>
                </TouchableOpacity>
              </View>
            </View>
            {/* 是否限量 */}
            <View style={styles.packing}>
              <View style={styles.itemHeader}>
                <Text
                  style={{
                    fontSize: px2dp(28),
                    fontWeight: 'bold',
                    color: mainBgColorBlack,
                  }}
                >
                  发货量
                  {' '}
                </Text>
              </View>
              <View style={styles.weightSelect}>
                <TextInput
                  placeholder='必填，请输入数量'
                  style={[
                    styles.goodsWrapPriceTextInput,
                    { color: fontColorBlack },
                  ]}
                  defaultValue={weight || ''}
                  value={weight || ''}
                  underlineColorAndroid='transparent'
                  onChangeText={(text) => {
                    this.onChangeWeight(text);
                  }}
                  keyboardType={
                    Platform.OS === 'android' ? 'numeric' : 'decimal-pad'
                  }
                  onBlur={() => { }}
                />
                <Text style={{ color: fontColorDeepGray }}>
                  {(item.weightUnit && unitList) ?
                    this.matchingUnit(item.weightUnit, unitList) : ''}
                </Text>
              </View>
              {/* <View style={styles.packingSelect}>
                  {!!unitList.length &&
                    unitList.map((item) => {
                      return (
                        <SelectItem
                          name={item.name}
                          type={'weightUnit'}
                          value={item.name}
                          activeVal={weightUnit}
                          maxLength={1}
                          onChange={(type, value) =>
                            this.onChange(type, value)
                          }
                          style={{width: px2dp(screenWidth * 0.4)}}
                        />
                      );
                    })}
              </View> */}
            </View>
          </View>
        </ScrollView>
        <View style={styles.submitStyle}>
          <Submit
            text='提交'
            boxStyle={styles.boxStyle}
            btnTextStyle={{
              fontSize: px2dp(36),
            }}
            onClick={() => {
              this.contractOrderCreat();
            }}
            disabled={disabled}
          />
        </View>

        <DateTimePicker
          isVisible={isTimeShow}
          mode='date'
          cancelTextIOS='取消'
          confirmTextIOS='确认'
          headerTextIOS='选取日期'
          locale='zh_CN'
          onConfirm={(val) => {
            this.handleConfirm(val);
          }}
          onCancel={() => {
            this.handleCancel();
          }}
        />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  submitStyle: {
    flex: 1,
    alignItems: 'center',
  },
  textDir: {
    textAlign: 'left',
    color: fontColorSecDeepGray,
  },
  labelWidth: {
    width: 120,
  },
  floorWrap: {
    borderRadius: px2dp(12),
    marginLeft: px2dp(24),
    marginRight: px2dp(24),
    overflow: 'hidden',
    marginTop: px2dp(24),
    // height: px2dp(400),
    backgroundColor: mainBgColorWhite
  },
  itemHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  packing: {
    marginTop: px2dp(48),
    marginLeft: px2dp(24),
    marginRight: px2dp(24),
  },
  startAndEndTimeWrap: {
    fontSize: px2dp(28),
    height: px2dp(72),
    width: '42%',
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: px2dp(4),
  },
  timeLine: {
    width: px2dp(32),
    height: 1,
    backgroundColor: splitLineColorLightGray,
    marginHorizontal: px2dp(30),
  },
  weightSelect: {
    marginTop: px2dp(24),
    paddingHorizontal: px2dp(24),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(4),
    marginBottom: px2dp(24 * 2)
  },
  goodsWrapPriceTextInput: {
    fontSize: px2dp(28),
    height: px2dp(72),
    width: '80%',
    backgroundColor: mainBgColorLightGray,
    paddingTop: 0,
    paddingBottom: 0,
  },
  packingSelect: {
    marginTop: px2dp(24),
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderRadius: px2dp(12),
    marginVertical: px2dp(100),
    overflow: 'hidden',
  }
});
